package com.lora.service.resolver;

import com.acooly.core.utils.Dates;
import com.google.common.collect.Maps;
import com.lora.dto.EquipmentDto;
import com.lora.entity.AirConditioningUps;
import com.lora.entity.AlarmList;
import com.lora.service.AirConditioningUpsService;
import com.lora.service.AlarmListService;
import com.lora.service.NodeDataResolver;
import com.lora.util.AirConditioningUpsMapping;
import com.lora.util.ClassFormatUtil;
import com.lora.util.StringUtil;
import com.lora.web.BaseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("airConditioningUpsResolver")
public class AirConditioningUpsResolver implements NodeDataResolver<AirConditioningUps> {

    @Resource
    AirConditioningUpsService airConditioningUpsService;

    @Resource
    private AlarmListService alarmListService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public EquipmentDto<AirConditioningUps> resolve(String equipmentNumber, String data) {
        data = BaseUtil.base64ToHex(data);
        EquipmentDto<AirConditioningUps> equipmentDto=new EquipmentDto<>();
        AirConditioningUps airConditioningUps=new AirConditioningUps();
        airConditioningUps.setDataString(data);
        Map<String,String> map=new HashMap<>();
        data=data.substring(6);
        System.out.println(data);
        String machine=data.substring(0,2);  //获取设备机号
        airConditioningUps.setEquipmentid(equipmentNumber);
        String suffer=data.substring(3,4);  //获取设备功能码
        Integer datalength=Integer.parseInt(data.substring(4,6),16);//获取数据长度
        String crcCode=data.substring(data.length()-4);
        data=data.substring(6,data.length()-4);//去掉前6位和后4位   保留数据长度2位和数据
        if(suffer.equals("1")){//功能码位1或2 是字节长度为1  占2位
            for (int i = 1; i <= datalength; i++) {
                String eiget = data.substring(2 * (i - 1), 2 * i);
                String two=reback(StringUtil.hexStringToByte(eiget));
                for (int j = 1; j <=8 ; j++) {
                    int address= 8*(i-1)+34+j;
                    String filed = AirConditioningUpsMapping.getFiled(suffer + address);
                    if(filed==null) continue;
                    map.put(filed,Integer.parseInt(two.substring((j-1),j))+"");
                }
            }

        }
        if(suffer.equals("3")){//功能码位3或4 是字节长度为2  占2位
            if(datalength==2){
                String filed = AirConditioningUpsMapping.getFiled(suffer + 54);
                map.put(filed,Integer.parseInt(data)+"");
            }else {
                for (int i = 1; i <= datalength/2; i++) {
                    int address = Integer.parseInt(suffer + i);
                    String filed = AirConditioningUpsMapping.getFiled(address+"");
                    if (filed == null) continue;
                    String sub = data.substring(4 * (i - 1), 4 * i);
                    map.put(filed, Integer.parseInt(sub,16) + "");
                }
            }
        }
        if(map!=null&&map.size()>0) {
            airConditioningUps.setRecordtime(StringUtil.dateToStr(new Date()));
            ClassFormatUtil.setFiledValue(map, airConditioningUps);
            equipmentDto.setEntity(airConditioningUps);
        }
        return equipmentDto;
    }

    @Override
    public AirConditioningUps save(AirConditioningUps equipment, boolean alarmFlag) {
        equipment.setAlarmFlag(alarmFlag);
        if(equipment.getReturnairtemperaturenumber()==null||equipment.getReturnairtemperaturenumber().equals("")){
            Map<String,Object> map =new HashMap<>();
            List<AirConditioningUps> query = airConditioningUpsService.query(map, null);
            if(query!=null){
                AirConditioningUps airConditioningUps = query.get(0);
                equipment.setId(airConditioningUps.getId());
                equipment.setDataString(equipment.getDataString()+","+airConditioningUps.getDataString());
                airConditioningUpsService.update(equipment);
                equipment = airConditioningUpsService.get(airConditioningUps.getId());
            }
        }else {
            airConditioningUpsService.save(equipment);
        }
        this.alarm(equipment);
        return equipment;
    }

    private String reback(String str){
        StringBuffer sb = new StringBuffer();
        char[] ch = str.toCharArray();
        for(int i = ch.length-1;i>=0;i--){
            sb.append(ch[i]);
        }
        return new String(sb);
    }

    private void alarm(AirConditioningUps airConditioningUps) {
        // 本地关机，远程关机
        if(airConditioningUps.getAirconditioningrunstate() != null) {
            if("0".equals(airConditioningUps.getAirconditioningrunstate()) ||
                    "1".equals(airConditioningUps.getAirconditioningrunstate())) {
                redisTemplate.opsForHash().put(airConditioningUps.getEquipmentid(), "shutDown", "true");
                if("ffffff100000f110".equals(airConditioningUps.getEquipmentid())) {
                    Map<String, Object> condition = Maps.newHashMap();
                    condition.put("EQ_epId", "ffffff100000f110");
                    condition.put("GTE_createTime", Dates.format(new Date(), Dates.CHINESE_DATE_FORMAT_LINE) + " 00:00:00");
                    List<AlarmList> query1 = alarmListService.query(condition, null);
                    if(query1.size()>0){
                        return;
                    }
                    // 如果当前设备处理关机状态，则检测另外一台是否也牌处于关机状态
                    if(redisTemplate.opsForHash().hasKey("ffffff100000f10d", "shutDown")) {
                        //this.saveAlarm(airConditioningUps);
                    }
                } else if("ffffff100000f10d".equals(airConditioningUps.getEquipmentid())) {
                    Map<String, Object> condition = Maps.newHashMap();
                    condition.put("EQ_epId", "ffffff100000f10d");
                    condition.put("GTE_createTime", Dates.format(new Date(), Dates.CHINESE_DATE_FORMAT_LINE) + " 00:00:00");
                    List<AlarmList> query1 = alarmListService.query(condition, null);
                    if(query1.size()>0){
                        return;
                    }
                    if(redisTemplate.opsForHash().hasKey("ffffff100000f110", "shutDown")) {
                       // this.saveAlarm(airConditioningUps);
                    }
                }
            } else {
                redisTemplate.delete(airConditioningUps.getEquipmentid());
            }
        }
    }

    private void saveAlarm(AirConditioningUps airConditioningUps) {
        AlarmList alarmList = new AlarmList();
        alarmList.setEpId(airConditioningUps.getEquipmentid());
        alarmList.setAlarmInfo("两台空调都处于关机状态");
        alarmList.setHandleStatus(0);
        alarmList.setFieldTitle("airconditioningrunstate");
        alarmList.setFieldName("空调运行状态");
        alarmListService.save(alarmList);
    }
}
